package com.lemeng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.lemeng.dao.SkuMapper;
import com.lemeng.entity.PageResult;
import com.lemeng.pojo.OrderItem;
import com.lemeng.pojo.Sku;
import com.lemeng.service.SkuService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SkuService.class)
public class SkuServiceImpl implements SkuService {

    @Autowired
    SkuMapper skuMapper;
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public List<Sku> findAll() {
        return skuMapper.selectAll();
    }

    @Override
    public PageResult<Sku> findPage(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        PageInfo<Sku> skuPageInfo = new PageInfo<>(skuMapper.selectAll());
//        Page<Sku> skus = (Page<Sku>)skuMapper.selectAll();
        return new PageResult(skuPageInfo.getTotal(),skuPageInfo.getList());
    }

    @Override
    public List<Sku> findList(Map<String, Object> serchMap) {
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        if (serchMap != null) {
            if (serchMap.get("name")!=null && StringUtil.isNotEmpty(serchMap.get("name").toString())){
                criteria.andLike("name","%"+serchMap.get("name").toString()+"%");
            }
            if (serchMap.get("letter")!=null && StringUtil.isNotEmpty(serchMap.get("letter").toString())){
                criteria.andEqualTo("letter",serchMap.get("letter").toString());
            }
        }
        return skuMapper.selectByExample(example);
    }

    @Override
    public PageResult<Sku> findPage(Integer page, Integer size, Map<String, Object> serchMap) {
        PageHelper.startPage(page,size);
        PageInfo<Sku> skuPageInfo = new PageInfo<>(findList(serchMap));
        return new PageResult(skuPageInfo.getTotal(),skuPageInfo.getList());
    }

    @Override
    public Sku findById(String id) {
        return skuMapper.selectByPrimaryKey(id);
    }

    @Override
    public void add(Sku sku) {
        skuMapper.insert(sku);
    }

    @Override
    public void update(Sku sku) {
        skuMapper.updateByPrimaryKeySelective(sku);
    }

    @Override
    public void delete(Integer id) {
        skuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void importDateToes(){
        Sku sku = new Sku();
        sku.setStatus("1");
        List<Sku> skuList = skuMapper.select(sku);
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.
                builder(new HttpHost("localhost", 9200)));

        BulkRequest bulkRequest = new BulkRequest();

        for (Sku sku1 : skuList) {
            IndexRequest indexRequest = new IndexRequest("sku", "doc", sku1.getId());
            HashMap hashMap = new HashMap();
            hashMap.put("name",sku1.getName());
            hashMap.put("brandName",sku1.getBrandName());
            hashMap.put("categoryName",sku1.getCategoryName());
            hashMap.put("price",sku1.getPrice());
            hashMap.put("createTime",sku1.getCreateTime());
            hashMap.put("spec", JSONObject.parseObject(sku1.getSpec()));
            hashMap.put("image",sku1.getImage());
            hashMap.put("saleNum",sku1.getSaleNum());
            hashMap.put("commentNum",sku1.getCommentNum());

            indexRequest.source(hashMap);

            bulkRequest.add(indexRequest);
        }

        try {
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

            restHighLevelClient.close();
        } catch (IOException e) {
            e.printStackTrace();
     }
   }

    @Override
    @Transactional
    public Boolean koujianKucun(List<OrderItem> orderItemList) {

        boolean flag = true;
        for (OrderItem orderItem : orderItemList) {
            Sku sku = skuMapper.selectByPrimaryKey(orderItem.getSkuId());
            if (sku==null){
                flag = false;
                break;
            }
            if (!"1".equals(sku.getStatus())){
                flag = false;
                break;
            }
            if (sku.getNum()<orderItem.getNum()){
                flag = false;
                break;
            }
        }

        if (flag){

            for (OrderItem orderItem : orderItemList) {

                skuMapper.koujiankucun(orderItem.getSkuId(),orderItem.getNum());
                skuMapper.addSaleNum(orderItem.getSkuId(),orderItem.getNum());
            }
        }
        return flag;
    }


}
